package cn.bearspark.emoji.provider.dao.buffer;

import cn.bearspark.emoji.provider.dao.key.EmojiBufferKeyBuilder;
import cn.bearspark.framework.redis.starter.buffer.RedisBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 表情包的缓存器
 *
 * @author f
 */
@Component
public class EmojiBuffer extends RedisBuffer {

    /**
     * 表情包缓存的过期时长，默认为 25h
     */
    private static final int EMOJI_CACHE_EXPIRE = 25;

    private final String emojiCacheKey;

    public EmojiBuffer(RedisTemplate<String, Object> redisTemplate,
                       EmojiBufferKeyBuilder emojiBufferKeyBuilder) {
        super(redisTemplate);
        this.emojiCacheKey = emojiBufferKeyBuilder.buildEmojiSetKey();
    }

    /**
     * 获取所有表情包的路径
     *
     * @return 所有表情包的路径
     */
    public Set<Object> listAllEmojiUrl() {
        return redisTemplate.opsForHash().keys(emojiCacheKey);
    }

    /**
     * 将表情包的路径转换为表情包的 id
     *
     * @param emojiUrl 表情包的路径
     * @return 表情包路径对应的 id
     */
    public long convertToEmojiId(String emojiUrl) {
        return super.objToLong(redisTemplate.opsForHash().get(emojiCacheKey, emojiUrl));
    }

    /**
     * 缓存指定的表情包映射
     *
     * @param emojiMap 指定的表情包映射，key：表情包的路径，value：表情包的 id
     */
    public void caching(Map<String, Long> emojiMap) {
        redisTemplate.opsForHash().putAll(emojiCacheKey, emojiMap);
        redisTemplate.expire(emojiCacheKey, EMOJI_CACHE_EXPIRE, TimeUnit.HOURS);
    }
}
